package com.cn.shuangzi.ad.manager;

import android.app.Activity;

import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.GMAdEcpmInfo;
import com.bytedance.msdk.api.v2.GMMediationAdSdk;
import com.bytedance.msdk.api.v2.GMSettingConfigCallback;
import com.bytedance.msdk.api.v2.ad.interstitial.GMInterstitialAd;
import com.bytedance.msdk.api.v2.ad.interstitial.GMInterstitialAdListener;
import com.bytedance.msdk.api.v2.ad.interstitial.GMInterstitialAdLoadCallback;
import com.bytedance.msdk.api.v2.slot.GMAdOptionUtil;
import com.bytedance.msdk.api.v2.slot.GMAdSlotInterstitial;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.util.SZUtil;

import java.util.List;

import androidx.annotation.NonNull;

public class AdInterstitialManager {

    private Activity mActivity;
    private GMInterstitialAd mInterstitialAd;
    private GMInterstitialAdLoadCallback mGMInterstitialAdLoadCallback;

    private String mAdUnitId; //广告位
    private String scenarioId; //广告位

    public AdInterstitialManager(Activity activity, GMInterstitialAdLoadCallback interstitialAdLoadCallback) {
        mActivity = activity;
        mGMInterstitialAdLoadCallback = interstitialAdLoadCallback;
    }

    public GMInterstitialAd getInterstitialAd() {
        return mInterstitialAd;
    }
    public void showAd(final Class<?> classVip, boolean isOnceShowVip){
        if(mInterstitialAd == null){
            return;
        }
        mInterstitialAd.setAdInterstitialListener(new GMInterstitialAdListener() {
            @Override
            public void onInterstitialShow() {

            }

            @Override
            public void onInterstitialShowFail(@NonNull AdError adError) {

            }

            @Override
            public void onInterstitialAdClick() {

            }

            @Override
            public void onInterstitialClosed() {
                if(classVip!=null&&!mActivity.isFinishing()) {
                    new AlertVipDialog(mActivity, classVip).show();
                }
            }

            @Override
            public void onAdOpened() {

            }

            @Override
            public void onAdLeftApplication() {

            }
        });
        mInterstitialAd.showAd(mActivity);
    }

    public void loadAdWithCallback(String adUnitId,String scenarioId) {
        this.mAdUnitId = adUnitId;
        this.scenarioId = scenarioId;
        /**
         * 判断当前是否存在config 配置 ，如果存在直接加载广告 ，如果不存在则注册config加载回调
         */
        if (GMMediationAdSdk.configLoadSuccess()) {
            SZUtil.logError("load ad 当前config配置存在，直接加载广告");
            loadInteractionAd();
        } else {
            SZUtil.logError("load ad 当前config配置不存在，正在请求config配置....");
            ADManager.getInstance().initGMAd();
            GMMediationAdSdk.registerConfigCallback(mSettingConfigCallback); //不用使用内部类，否则在ondestory中无法移除该回调
        }
    }

    /**
     * 加载插屏广告
     */
    private void loadInteractionAd() {
        //Context 必须传activity
        /**
         * 注：每次加载插屏广告的时候需要新建一个GMInterstitialAd，否则可能会出现广告填充问题
         * （ 例如：mInterstitialAd = new GMInterstitialAd(this, adUnitId);）
         */
        mInterstitialAd = new GMInterstitialAd(mActivity, mAdUnitId);

        GMAdSlotInterstitial adSlotInterstitial = new GMAdSlotInterstitial.Builder()
                .setGMAdSlotBaiduOption(GMAdOptionUtil.getGMAdSlotBaiduOption().build())
                .setGMAdSlotGDTOption(GMAdOptionUtil.getGMAdSlotGDTOption().build())
                .setImageAdSize(600, 600)
                .setMuted(true)
                .setScenarioId(scenarioId)
                .setVolume(0f)
                .build();

        //请求广告，调用插屏广告异步请求接口
        mInterstitialAd.loadAd(adSlotInterstitial, mGMInterstitialAdLoadCallback);
    }

    public void destroy() {
        if (mInterstitialAd != null) {
            mInterstitialAd.destroy();
        }
        mActivity = null;
        mGMInterstitialAdLoadCallback = null;
        GMMediationAdSdk.unregisterConfigCallback(mSettingConfigCallback); //注销config回调
    }


    /**
     * config回调
     */
    private GMSettingConfigCallback mSettingConfigCallback = new GMSettingConfigCallback() {
        @Override
        public void configLoad() {
            SZUtil.logError("load ad 在config 回调中加载广告");
            loadInteractionAd();
        }
    };


    //-----------以下方法非必须 ，按需使用--------------

    //打印已经加载广告的信息
    public void printLoadAdInfo() {
        if (mInterstitialAd == null) {
            return;
        }
        /**
         * 获取已经加载的clientBidding ，多阶底价广告的相关信息
         */
        List<GMAdEcpmInfo> gmAdEcpmInfos = mInterstitialAd.getMultiBiddingEcpm();
        if (gmAdEcpmInfos != null) {
            for (GMAdEcpmInfo info : gmAdEcpmInfos) {
                SZUtil.logError("***多阶+client相关信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }

        /**
         * 获取实时填充/缓存池中价格最优的代码位信息即相关价格信息，每次只有一个信息
         */
        GMAdEcpmInfo gmAdEcpmInfo = mInterstitialAd.getBestEcpm();
        if (gmAdEcpmInfo != null) {
            SZUtil.logError("***实时填充/缓存池中价格最优的代码位信息*** AdNetworkPlatformId" + gmAdEcpmInfo.getAdNetworkPlatformId()
                    + "  AdNetworkRitId:" + gmAdEcpmInfo.getAdNetworkRitId()
                    + "  ReqBiddingType:" + gmAdEcpmInfo.getReqBiddingType()
                    + "  PreEcpm:" + gmAdEcpmInfo.getPreEcpm()
                    + "  LevelTag:" + gmAdEcpmInfo.getLevelTag()
                    + "  ErrorMsg:" + gmAdEcpmInfo.getErrorMsg()
                    + "  request_id:" + gmAdEcpmInfo.getRequestId());
        }

        /**
         * 获取获取当前缓存池的全部信息
         */
        List<GMAdEcpmInfo> gmCacheInfos = mInterstitialAd.getCacheList();
        if (gmCacheInfos != null) {
            for (GMAdEcpmInfo info : gmCacheInfos) {
                SZUtil.logError("***缓存池的全部信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }
    }

    //打印加载失败的adn错误信息
    public void printLoadFailAdnInfo() {
        if (mInterstitialAd == null) {
            return;
        }

        // 获取本次waterfall加载中，加载失败的adn错误信息。
        SZUtil.logError( "reward ad loadinfos: " + mInterstitialAd.getAdLoadInfoList());
    }

    //打印已经展示的广告信息
    public void printShowAdInfo() {
        if (mInterstitialAd == null) {
            return;
        }
        GMAdEcpmInfo gmAdEcpmInfo = mInterstitialAd.getShowEcpm();
        if (gmAdEcpmInfo == null) {
            return;
        }
        SZUtil.logError( "展示的广告信息 ： adNetworkPlatformName: " + gmAdEcpmInfo.getAdNetworkPlatformName() + "   adNetworkRitId：" + gmAdEcpmInfo.getAdNetworkRitId() + "   preEcpm: " + gmAdEcpmInfo.getPreEcpm());
    }
}
